package cn.Alibaba.system.service.impl;


import cn.Alibaba.system.domain.Menu;
import cn.Alibaba.system.mapper.MenuMapper;
import cn.Alibaba.system.service.IMenuService;
import cn.Alibaba.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuTree() {
        List<Menu> menus = menuMapper.loadAll();
        Map<Long,Menu> map = new HashMap<>();
        for (Menu menu : menus) {
            map.put(menu.getId(),menu);
        }

        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParent_id() == null) {
                menuTree.add(menu);
            } else {
                Long parentId = menu.getParent_id();
                Menu menuParent = map.get(parentId);
                menuParent.getChildren().add(menu);
            }
        }

        return menuTree;

    }
}
